import { useEffect, useState } from "react";
import Navigate from "../components/Navigate.jsx";
import "./Management.css";
import {
  listAssessmentRulesService,
  createAssessmentRuleService,
  updateAssessmentRuleService,
  deleteAssessmentRuleService,
  toggleRuleStatusService,
  getAssessmentStatisticsService,
  executeManualAssessmentService,
  getMetricTypesService,
  getPenaltyTypesService
} from "../api/AdminApi";

function AssessmentManagement() {
  const [allRules, setAllRules] = useState([]); // 存储所有规则
  const [rules, setRules] = useState([]); // 存储筛选后的规则
  const [statistics, setStatistics] = useState([]);
  const [metricTypes, setMetricTypes] = useState([]);
  const [penaltyTypes, setPenaltyTypes] = useState([]);
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState({
    current: 1,
    size: 10,
    total: 0,
  });
  const [statisticsPagination, setStatisticsPagination] = useState({
    current: 1,
    size: 6,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState({
    isActive: "all",
    page: 1,
    pageSize: 10,
  });
  const [showRuleModal, setShowRuleModal] = useState(false);
  const [currentRule, setCurrentRule] = useState(null);
  const [showExecuteModal, setShowExecuteModal] = useState(false);
  const [executeParams, setExecuteParams] = useState({
    userId: "",
    ruleId: "",
    forceAssess: false,
  });

  // 获取考核规则列表
  const fetchRules = async () => {
    setLoading(true);
    try {
      const res = await listAssessmentRulesService({ page: 1, pageSize: 1000 }); // 获取所有规则
      if (res.status === 200) {
        setAllRules(res.data.records || []);
        // 应用筛选
        applyFilters(res.data.records || []);
      }
    } catch (error) {
      console.error("获取考核规则列表失败:", error);
      setAllRules([]);
      setRules([]);
    } finally {
      setLoading(false);
    }
  };

  // 应用筛选
  const applyFilters = (data) => {
    let filteredData = [...data];
    
    // 应用状态筛选
    if (searchParams.isActive !== "all") {
      filteredData = filteredData.filter(
        rule => rule.isActive === Number(searchParams.isActive)
      );
    }

    // 更新分页信息
    const total = filteredData.length;
    const start = (searchParams.page - 1) * searchParams.pageSize;
    const end = start + searchParams.pageSize;
    
    // 更新分页后的数据
    setRules(filteredData.slice(start, end));
    setPagination({
      current: searchParams.page,
      size: searchParams.pageSize,
      total: total,
    });
  };

  // 获取考核统计数据
  const fetchStatistics = async () => {
    try {
      const res = await getAssessmentStatisticsService();
      if (res.status === 200) {
        setStatistics(res.data || []);
        setStatisticsPagination(prev => ({
          ...prev,
          total: (res.data || []).length
        }));
      }
    } catch (error) {
      console.error("获取考核统计数据失败:", error);
      setStatistics([]);
    }
  };

  // 获取指标类型和惩罚类型
  const fetchTypes = async () => {
    try {
      const [metricRes, penaltyRes] = await Promise.all([
        getMetricTypesService(),
        getPenaltyTypesService(),
      ]);
      if (metricRes.status === 200) {
        setMetricTypes(metricRes.data || []);
      }
      if (penaltyRes.status === 200) {
        setPenaltyTypes(penaltyRes.data || []);
      }
    } catch (error) {
      console.error("获取类型数据失败:", error);
    }
  };

  useEffect(() => {
    fetchRules();
    fetchStatistics();
    fetchTypes();
  }, [searchParams]);

  // 处理搜索参数变化
  const handleSearchChange = (e) => {
    const { name, value } = e.target;
    setSearchParams((prev) => ({
      ...prev,
      [name]: value,
      page: 1,
    }));
  };

  // 重置搜索
  const handleReset = () => {
    setSearchParams({
      isActive: "all",
      page: 1,
      pageSize: 10,
    });
  };

  // 分页处理
  const handlePageChange = (page) => {
    setSearchParams((prev) => ({
      ...prev,
      page: page,
    }));
  };

  const handlePageSizeChange = (size) => {
    setSearchParams((prev) => ({
      ...prev,
      pageSize: size,
      page: 1,
    }));
  };

  // 监听搜索参数变化，重新应用筛选
  useEffect(() => {
    if (allRules.length > 0) {
      applyFilters(allRules);
    }
  }, [searchParams, allRules]);

  // 处理规则创建/编辑
  const handleRuleSubmit = async (e) => {
    e.preventDefault(); // 阻止表单默认提交
    try {
      const ruleData = {
        ...currentRule,
        isActive: currentRule?.isActive ?? 1, // 默认启用
        priority: currentRule?.priority ?? 100, // 默认优先级
      };

      if (currentRule?.id) {
        await updateAssessmentRuleService(ruleData);
      } else {
        await createAssessmentRuleService(ruleData);
      }
      
      // 重新获取数据
      await fetchRules();
      await fetchStatistics();
      
      // 关闭弹窗并重置状态
      setShowRuleModal(false);
      setCurrentRule(null);
    } catch (error) {
      console.error("保存规则失败:", error);
      alert("保存失败：" + (error.response?.data?.message || error.message));
    }
  };

  // 处理规则删除
  const handleDeleteRule = async (ruleId) => {
    if (!window.confirm("确定要删除该规则吗？")) return;
    try {
      await deleteAssessmentRuleService(ruleId);
      fetchRules(); // 重新获取所有规则
    } catch (error) {
      console.error("删除规则失败:", error);
    }
  };

  // 处理规则状态切换
  const handleToggleStatus = async (ruleId, isActive) => {
    try {
      await toggleRuleStatusService(ruleId, isActive);
      fetchRules(); // 重新获取所有规则
    } catch (error) {
      console.error("切换规则状态失败:", error);
    }
  };

  // 处理手动执行考核
  const handleExecuteAssessment = async () => {
    try {
      await executeManualAssessmentService(executeParams);
      setShowExecuteModal(false);
      setExecuteParams({
        userId: "",
        ruleId: "",
        forceAssess: false,
      });
    } catch (error) {
      console.error("执行考核失败:", error);
    }
  };

  // 处理统计分页变化
  const handleStatisticsPageChange = (page) => {
    setStatisticsPagination(prev => ({
      ...prev,
      current: page
    }));
  };

  // 处理统计每页条数变化
  const handleStatisticsPageSizeChange = (size) => {
    setStatisticsPagination(prev => ({
      ...prev,
      size: size,
      current: 1
    }));
  };

  // 计算当前页的统计数据
  const getCurrentPageStatistics = () => {
    const start = (statisticsPagination.current - 1) * statisticsPagination.size;
    const end = start + statisticsPagination.size;
    return statistics.slice(start, end);
  };

  return (
    <div className="admin-layout">
      <Navigate activeItem="考核管理" />
      <div className="main-content">
        <div className="management-container">
          <div className="header">
            <h2>考核管理</h2>
            <div className="header-actions">
              <button
                className="btn btn-primary"
                onClick={() => {
                  setCurrentRule(null);
                  setShowRuleModal(true);
                }}
              >
                新建规则
              </button>
              <button
                className="btn btn-secondary"
                onClick={() => setShowExecuteModal(true)}
              >
                执行考核
              </button>
            </div>
          </div>

          {/* 搜索表单 */}
          <div className="search-form">
            <div className="form-group">
              <label>规则状态</label>
              <select
                name="isActive"
                value={searchParams.isActive}
                onChange={handleSearchChange}
                className="form-select"
              >
                <option value="all">全部</option>
                <option value="1">启用</option>
                <option value="0">禁用</option>
              </select>
            </div>
            <div className="form-group">
              <button className="btn btn-secondary" onClick={handleReset}>
                重置
              </button>
            </div>
          </div>

          {/* 规则列表 */}
          <div className="table-container">
            <table className="table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>规则名称</th>
                  <th>考核指标</th>
                  <th>达标阈值</th>
                  <th>考核周期</th>
                  <th>惩罚措施</th>
                  <th>优先级</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={9} style={{ textAlign: "center" }}>加载中...</td>
                  </tr>
                ) : rules.length === 0 ? (
                  <tr>
                    <td colSpan={9} style={{ textAlign: "center" }}>暂无数据</td>
                  </tr>
                ) : (
                  rules.map((rule) => (
                    <tr key={rule.id}>
                      <td>{rule.id}</td>
                      <td>{rule.name}</td>
                      <td>{rule.metric}</td>
                      <td>{rule.threshold}</td>
                      <td>{rule.cycleDays}天</td>
                      <td>{rule.penalty}</td>
                      <td>{rule.priority}</td>
                      <td>
                        <span
                          className={`status-badge ${
                            rule.isActive === 1 ? "status-normal" : "status-banned"
                          }`}
                        >
                          {rule.isActive === 1 ? "启用" : "禁用"}
                        </span>
                      </td>
                      <td>
                        <div className="action-buttons">
                          <button
                            className="btn btn-primary"
                            onClick={() => {
                              setCurrentRule(rule);
                              setShowRuleModal(true);
                            }}
                          >
                            编辑
                          </button>
                          <button
                            className="btn btn-danger"
                            onClick={() => handleDeleteRule(rule.id)}
                          >
                            删除
                          </button>
                          <button
                            className="btn btn-secondary"
                            onClick={() =>
                              handleToggleStatus(rule.id, rule.isActive === 1 ? 0 : 1)
                            }
                          >
                            {rule.isActive === 1 ? "禁用" : "启用"}
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          {/* 分页 */}
          <div className="pagination-container">
            <div className="pagination-info">共 {pagination.total} 条数据</div>
            <div className="pagination-controls">
              <button
                onClick={() => handlePageChange(pagination.current - 1)}
                disabled={pagination.current === 1}
                className="pagination-btn"
              >
                ‹
              </button>
              {[...Array(Math.ceil(pagination.total / pagination.size)).keys()].map((i) => (
                <button
                  key={i + 1}
                  className={`pagination-btn ${pagination.current === i + 1 ? "active" : ""}`}
                  onClick={() => handlePageChange(i + 1)}
                >
                  {i + 1}
                </button>
              ))}
              <button
                onClick={() => handlePageChange(pagination.current + 1)}
                disabled={pagination.current === Math.ceil(pagination.total / pagination.size)}
                className="pagination-btn"
              >
                ›
              </button>
              <div className="pagination-jump">
                <select
                  value={pagination.size}
                  onChange={(e) => handlePageSizeChange(Number(e.target.value))}
                >
                  {[10, 20, 50, 100].map((size) => (
                    <option key={size} value={size}>
                      {size} 条/页
                    </option>
                  ))}
                </select>
                <span>跳至</span>
                <input
                  type="number"
                  min={1}
                  max={Math.ceil(pagination.total / pagination.size)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      const page = Number(e.target.value);
                      if (page >= 1 && page <= Math.ceil(pagination.total / pagination.size)) {
                        handlePageChange(page);
                      }
                    }
                  }}
                  placeholder="页码"
                />
                <span>页</span>
              </div>
            </div>
          </div>

          {/* 考核统计 */}
          <div className="statistics-section">
            <h3>考核统计</h3>
            <div className="statistics-grid">
              {getCurrentPageStatistics().map((stat) => (
                <div key={stat.ruleId} className="statistics-card">
                  <h4>{stat.ruleName}</h4>
                  <div className="statistics-content">
                    <div className="stat-item">
                      <span className="stat-label">总考核人数</span>
                      <span className="stat-value">{stat.totalAssessed || 0}</span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">通过率</span>
                      <span className="stat-value">
                        {((stat.passRate || 0) * 100).toFixed(1)}%
                      </span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">平均值</span>
                      <span className="stat-value">
                        {(stat.averageValue || 0).toFixed(2)}
                      </span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">通过人数</span>
                      <span className="stat-value">
                        {Math.round((stat.passRate || 0) * (stat.totalAssessed || 0))}
                      </span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">未通过人数</span>
                      <span className="stat-value">
                        {Math.round((1 - (stat.passRate || 0)) * (stat.totalAssessed || 0))}
                      </span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">最高值</span>
                      <span className="stat-value">
                        {(stat.maxValue || 0).toFixed(2)}
                      </span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            {/* 统计分页控件 */}
            <div className="pagination-container">
              <div className="pagination-info">共 {statisticsPagination.total} 条数据</div>
              <div className="pagination-controls">
                <button
                  onClick={() => handleStatisticsPageChange(statisticsPagination.current - 1)}
                  disabled={statisticsPagination.current === 1}
                  className="pagination-btn"
                >
                  ‹
                </button>
                {[...Array(Math.ceil(statisticsPagination.total / statisticsPagination.size)).keys()].map((i) => (
                  <button
                    key={i + 1}
                    className={`pagination-btn ${statisticsPagination.current === i + 1 ? "active" : ""}`}
                    onClick={() => handleStatisticsPageChange(i + 1)}
                  >
                    {i + 1}
                  </button>
                ))}
                <button
                  onClick={() => handleStatisticsPageChange(statisticsPagination.current + 1)}
                  disabled={statisticsPagination.current === Math.ceil(statisticsPagination.total / statisticsPagination.size)}
                  className="pagination-btn"
                >
                  ›
                </button>
                <div className="pagination-jump">
                  <select
                    value={statisticsPagination.size}
                    onChange={(e) => handleStatisticsPageSizeChange(Number(e.target.value))}
                  >
                    {[6, 12, 24, 36].map((size) => (
                      <option key={size} value={size}>
                        {size} 条/页
                      </option>
                    ))}
                  </select>
                  <span>跳至</span>
                  <input
                    type="number"
                    min={1}
                    max={Math.ceil(statisticsPagination.total / statisticsPagination.size)}
                    onKeyDown={(e) => {
                      if (e.key === "Enter") {
                        const page = Number(e.target.value);
                        if (page >= 1 && page <= Math.ceil(statisticsPagination.total / statisticsPagination.size)) {
                          handleStatisticsPageChange(page);
                        }
                      }
                    }}
                    placeholder="页码"
                  />
                  <span>页</span>
                </div>
              </div>
            </div>
          </div>

          {/* 规则编辑弹窗 */}
          {showRuleModal && (
            <div className="modal-overlay" onClick={() => setShowRuleModal(false)}>
              <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                  <h2>{currentRule ? "编辑规则" : "新建规则"}</h2>
                </div>
                <div className="modal-body">
                  <form onSubmit={handleRuleSubmit}>
                    <div className="form-group">
                      <label>规则名称</label>
                      <input
                        type="text"
                        className="form-input"
                        value={currentRule?.name || ""}
                        onChange={(e) =>
                          setCurrentRule({ ...currentRule, name: e.target.value })
                        }
                        required
                      />
                    </div>
                    <div className="form-group">
                      <label>考核指标</label>
                      <select
                        className="form-select"
                        value={currentRule?.metric || ""}
                        onChange={(e) =>
                          setCurrentRule({ ...currentRule, metric: e.target.value })
                        }
                        required
                      >
                        <option value="">请选择</option>
                        {metricTypes.map((type) => (
                          <option key={type.key} value={type.key}>
                            {type.name}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div className="form-group">
                      <label>达标阈值</label>
                      <input
                        type="number"
                        step="0.01"
                        min="0"
                        className="form-input"
                        value={currentRule?.threshold || ""}
                        onChange={(e) =>
                          setCurrentRule({
                            ...currentRule,
                            threshold: parseFloat(e.target.value) || 0,
                          })
                        }
                        required
                      />
                    </div>
                    <div className="form-group">
                      <label>考核周期（天）</label>
                      <input
                        type="number"
                        className="form-input"
                        value={currentRule?.cycleDays || ""}
                        onChange={(e) =>
                          setCurrentRule({
                            ...currentRule,
                            cycleDays: parseInt(e.target.value),
                          })
                        }
                        required
                      />
                    </div>
                    <div className="form-group">
                      <label>惩罚措施</label>
                      <select
                        className="form-select"
                        value={currentRule?.penalty || ""}
                        onChange={(e) =>
                          setCurrentRule({ ...currentRule, penalty: e.target.value })
                        }
                        required
                      >
                        <option value="">请选择</option>
                        {penaltyTypes.map((type) => (
                          <option key={type.name} value={type.name}>
                            {type.name}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div className="form-group">
                      <label>优先级</label>
                      <input
                        type="number"
                        className="form-input"
                        value={currentRule?.priority || 100}
                        onChange={(e) =>
                          setCurrentRule({
                            ...currentRule,
                            priority: parseInt(e.target.value),
                          })
                        }
                      />
                    </div>
                    <div className="form-group">
                      <label>规则描述</label>
                      <textarea
                        className="form-input"
                        value={currentRule?.description || ""}
                        onChange={(e) =>
                          setCurrentRule({ ...currentRule, description: e.target.value })
                        }
                        rows={4}
                      />
                    </div>
                    <div className="modal-footer">
                      <button type="submit" className="btn btn-primary">
                        保存
                      </button>
                      <button
                        type="button"
                        className="btn btn-secondary"
                        onClick={() => setShowRuleModal(false)}
                      >
                        取消
                      </button>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          )}

          {/* 执行考核弹窗 */}
          {showExecuteModal && (
            <div className="modal-overlay" onClick={() => setShowExecuteModal(false)}>
              <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                  <h2>执行考核</h2>
                </div>
                <div className="modal-body">
                  <div className="form-group">
                    <label>用户ID（可选）</label>
                    <input
                      type="text"
                      className="form-input"
                      value={executeParams.userId}
                      onChange={(e) =>
                        setExecuteParams({ ...executeParams, userId: e.target.value })
                      }
                      placeholder="留空则考核所有用户"
                    />
                  </div>
                  <div className="form-group">
                    <label>规则ID（可选）</label>
                    <select
                      className="form-select"
                      value={executeParams.ruleId}
                      onChange={(e) =>
                        setExecuteParams({ ...executeParams, ruleId: e.target.value })
                      }
                    >
                      <option value="">全部规则</option>
                      {rules.map((rule) => (
                        <option key={rule.id} value={rule.id}>
                          {rule.name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div className="form-group">
                    <label>
                      <input
                        type="checkbox"
                        checked={executeParams.forceAssess}
                        onChange={(e) =>
                          setExecuteParams({
                            ...executeParams,
                            forceAssess: e.target.checked,
                          })
                        }
                      />
                      强制考核（忽略周期）
                    </label>
                  </div>
                </div>
                <div className="modal-footer">
                  <button
                    className="btn btn-primary"
                    onClick={handleExecuteAssessment}
                  >
                    执行
                  </button>
                  <button
                    className="btn btn-secondary"
                    onClick={() => setShowExecuteModal(false)}
                  >
                    取消
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default AssessmentManagement; 